package com.ruoyi.common.config.websockert;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Fql18
 * @version 1.0
 * @date 2025-08-19 22:53
 * @description
 */
@Slf4j
public class ChatWsHandler extends TextWebSocketHandler {

	// 简单保存所有 Session，可自行替换成 Redis
	private final Map<String, WebSocketSession> clients = new ConcurrentHashMap<>();

	@Override
	public void afterConnectionEstablished(WebSocketSession session) {
		clients.put(session.getId(), session);
		log.info("客户端 {} 上线，当前在线：{}", session.getId(), clients.size());
	}

	@Override
	protected void handleTextMessage(WebSocketSession session, TextMessage message)
		throws IOException {
		String payload = message.getPayload();
		log.info("收到消息: {}", payload);
		// 解析 JSON 后转给目标用户（示例：群聊）
		for (WebSocketSession s : clients.values()) {
			if (s.isOpen()) {
				s.sendMessage(new TextMessage(payload));
			}
		}
	}

	@Override
	public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
		clients.remove(session.getId());
		log.info("客户端 {} 下线", session.getId());
	}
}
